package com.jzy.common.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

/**
 * @author jzy
 * @date 2020/8/22 9:01
 */
public class SsoClientUtil {

    private static Properties ssoProperties = new Properties();
    private static String SERVER_URL_PREFIX;//统一认证中心地址
    private static String CLIENT_HOST_URL;//当前客户端地址

    static {
        try {
            ssoProperties.load(SsoClientUtil.class.getClassLoader().getResourceAsStream("sso.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        SERVER_URL_PREFIX = ssoProperties.getProperty("server-url-prefix");
        CLIENT_HOST_URL = ssoProperties.getProperty("client-host-url");
    }

    /**
     * 当客户端请求被拦截,跳往统一认证中心,需要带redirectUrl的参数,统一认证中心登录后回调的地址
     */
    private static String getRedirectUrl(HttpServletRequest request){
        return CLIENT_HOST_URL + request.getServletPath();
    }

    /**
     * 根据request获取跳转统一认证中心的地址,通过response跳转到指定的地址
     */
    public static void redirectToSso(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String redirectUrl = getRedirectUrl(request);
        String url = SERVER_URL_PREFIX + "/login.html?redirect=" + redirectUrl;
        response.sendRedirect(url);
    }
}
